
package com.the9.C9Alarm;

import java.util.Calendar;

import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

public class SetAlarmActivity extends Activity {
    private final static String TAG                     = "alarm";
    private static final int TYPE_ALARM                 = 1;
    
    private Context mContext;
    
//    private AlarmBean m_alarm;
    
    ListView m_listViewAlarm;

    TextView m_tvAlarmName;
   // TextView m_tvAlarmTime;
    WheelView wlh,wlm;
    TextView m_tvAlarmWeeklyMode;
    TextView m_tvAlarmOccursMode;
    TextView m_tvAlarmInterval;
    TextView m_tvAlarmRingMode;

    Button m_btFinish, m_btBack;
    
    /** index of alarms */ 
    private int    m_alarmIndex                     = 0;

    private String m_alarmName                      = "";
    private int m_alarmType                         = 0;
    
    private boolean m_bNameManulShowed              = false;
    
    private String m_alarmWeekly                    = "";
    
    private String m_alarmOccurs                    = "";
    private String m_alarmInterval                  = "";
    
    private String m_alarmRingMode                  = "";
    
    /** the day which alarm occurs on */
    private int    m_nOccursDay                     = 0; //0x7f;
    
    private boolean m_bWeeklyManulSelected          = false;

    private int m_alarmHours                        = 0;
    private int m_alarmMinutes                      = 0;
    
    private boolean m_gameEnable                      ;
    private int m_nOccurs                           = 0;
    private int m_nInterval                         = 0;
    
    private int    m_nRingMode                      = 0;
    private String m_ringUri                        = null;

    private boolean m_bEnable                       = false;
    private boolean m_bVibrate                      = false;
    
    private int form;
    RelativeLayout mainFrame;
    Form f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.alarm_list);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.alarm_settings);
        mainFrame = (RelativeLayout) findViewById(R.id.main_frame);
        
        mContext = this;
        
        Bundle extras = getIntent().getExtras();
        m_alarmIndex = extras.getInt("alarm_position");
        Log.d("alarm", "get index: " + m_alarmIndex);
        
        

        AlarmBean alarm = AlarmProvider.geInstance(this).getAlarm(m_alarmIndex);
        
        initialParam(alarm);

        initView(alarm);
    }

    private void initialParam( final AlarmBean alarm ) {
    	f=Form.getForm(alarm.getForm());
    	if(f!=null){
    		//alarm.setUri(f.getAlarmMusic());
    		//alarm.setRingMode(Symbol.RING_SYSTEM);
    		
    	}
    	
        m_alarmIndex                     = alarm.getIndex();
        
        //init alarm name
        m_alarmType                      = alarm.getType();
	    m_alarmName                      = alarm.getName();
	    
// 	    m_alarmWeekly                    = alarm.getDay();
	    m_alarmOccurs                    = "";
	
	    m_nOccursDay                     = alarm.getDay();

	    Calendar c                       = Calendar.getInstance();
	    c.setTimeInMillis(alarm.getTime());
	    
	    m_alarmHours                     = c.get(Calendar.HOUR_OF_DAY);
	    m_alarmMinutes                   = c.get(Calendar.MINUTE);
	    
	    m_nRingMode                      = alarm.getRingMode();
	    
	    m_alarmRingMode                  = Utils.formatRingMode( m_nRingMode );
	    m_ringUri                        = alarm.getUri();
	    
	    m_nInterval                      = alarm.getSleepDelay();
	    
	    m_bEnable                        = alarm.getEnabled();
	    m_bVibrate                       = alarm.getVibrate();
	    m_gameEnable					 = alarm.getEnableGame();
	    form 						     = alarm.getForm();
    }
    
    public void initView(final AlarmBean alarm) {
    	
    	mainFrame.setBackgroundResource(f.getBackGround());
    	
        // set alarm name
        LinearLayout llAlarmName = (LinearLayout) findViewById(R.id.linearLayoutAlarmName);
        m_tvAlarmName = (TextView) findViewById(R.id.tvAlarmName);
        m_tvAlarmName.setText(m_alarmName);

        llAlarmName.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setAlarmName(alarm);
            }
        });

        LinearLayout llAlarmGame = (LinearLayout) findViewById(R.id.LinearLayoutAwakeGame);
        m_tvAlarmName = (TextView) findViewById(R.id.awakeGame);
        m_tvAlarmName.setText(m_gameEnable==false?"关闭":"开启");

        llAlarmGame.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	setGame(alarm);
            }
        });
       
          wlh = (WheelView) findViewById(R.id.hh);
        NumericWheelAdapter hourAdapter = new NumericWheelAdapter(this, 0, 23);
        
        hourAdapter.setItemResource(R.layout.wheel_text_item);
        hourAdapter.setItemTextResource(R.id.text);
        wlh.setViewAdapter(hourAdapter);
        wlh.setCyclic(true);
        wlh.setCurrentItem(m_alarmHours, false);
        
        
        wlm = (WheelView) findViewById(R.id.mm);
        NumericWheelAdapter minuteAdapter = new NumericWheelAdapter(this, 0, 59);
        
        minuteAdapter.setItemResource(R.layout.wheel_text_item);
        minuteAdapter.setItemTextResource(R.id.text);
        wlm.setViewAdapter(minuteAdapter);
        wlm.setCurrentItem(m_alarmMinutes, false);
        wlm.setCyclic(true);
       

        // set alarm weekly mode
        LinearLayout llAlarmWeeklyMode = (LinearLayout) findViewById(R.id.linearLayoutWeeklyMode);
        llAlarmWeeklyMode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setWeeklyDialog(alarm);
            }
        });

        m_tvAlarmWeeklyMode = (TextView) findViewById(R.id.tvAlarmWeekly);
        m_tvAlarmWeeklyMode.setText(Utils.FormatDay(m_nOccursDay));
        
        // TODO:
        // alarm ring occurs
        /*LinearLayout llAlarmOccursMode = (LinearLayout) findViewById(R.id.linearLayoutOccurs);
        llAlarmOccursMode.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //setOccursDialog( alarm );
                setIntervalDialog(alarm);
            }
        });
        
        m_tvAlarmOccursMode = (TextView) findViewById(R.id.tvAlarmOccurs);
        m_tvAlarmOccursMode.setText(m_nInterval+"分钟");*/
        
      //  m_tvAlarmTime.setText("")
        //alarm interval mode
//        m_tvAlarmInterval = (TextView) findViewById(R.id.tvAlarmOccurs);

        // alarm ring sound
        LinearLayout llAlarmRingMode = (LinearLayout) findViewById(R.id.linearLayoutRingMode);
        llAlarmRingMode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setAlarmRingDialog( alarm );
            }
        });
        
        m_tvAlarmRingMode = (TextView) findViewById(R.id.tvRingMode);
        m_tvAlarmRingMode.setText(m_alarmRingMode);

        // init buttons
        m_btFinish = (Button) findViewById(R.id.btFinish);
        m_btBack = (Button) findViewById(R.id.btBack);

        m_btFinish.setOnClickListener(oclButtons);
        m_btBack.setOnClickListener(oclButtons);
        
        
        if(f!=null){
        	llAlarmRingMode.setVisibility(View.INVISIBLE);
        	llAlarmName.setVisibility(View.INVISIBLE);
        	getWindow().setFeatureInt(  
                    Window.FEATURE_CUSTOM_TITLE,  //设置此样式为自定义样式  
                    R.layout.title //设置对应的布局  
                    );//自定义布局赋值   
        	
        	((TextView)this.findViewById(R.id.titleText)).setText(f.getTitleName());
        	((ImageView)this.findViewById(R.id.titleImg)).setImageResource(f.getTitleImg());// .setText(f.getTitleName());
    	}
    }

    public void setAlarmName( final AlarmBean alarm ) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_names, null);

        final Dialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.drawable.white_cloud)
                .setTitle(getString(R.string.alarm_name_title)).setView(layout)
                .setNegativeButton(getString(R.string.cancel), null)
                .create();

        dialog.show();
        
        RadioGroup rgAlarmName = (RadioGroup) layout.findViewById(R.id.rgAlarmNames);
        final RadioButton rbXiaoNao = (RadioButton) layout.findViewById(R.id.rbXiaoNao);
        final RadioButton rbXiaoLongMao = (RadioButton) layout.findViewById(R.id.rbXiaoLongMao);
        final RadioButton rbXiaoMeiQiu = (RadioButton) layout.findViewById(R.id.rbXiaoMeiQiu);
        final RadioButton rbManulInput = (RadioButton) layout.findViewById(R.id.rbManulInput);
        
        switch (m_alarmType) {
            case Symbol.TYPE_XIAONAO:
                m_tvAlarmName.setText(getString(R.string.alarm_name_xiaonao));
                rbXiaoNao.setChecked(true);
                break;
            case Symbol.TYPE_XIAOLONGMAO:
                m_tvAlarmName.setText(getString(R.string.alarm_name_xiaolongmao));
                rbXiaoLongMao.setChecked(true);
                break;
            case Symbol.TYPE_XIAOMEIQIU:
                m_tvAlarmName.setText(getString(R.string.alarm_name_xiaomeiqiu));
                rbXiaoMeiQiu.setChecked(true);
                break;
            case Symbol.TYPE_MANULINPUT:
                m_tvAlarmName.setText( alarm.getName() );
                rbManulInput.setChecked(true);
                break;
        }
        
        rgAlarmName.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbXiaoNao.getId()) {
                    m_alarmName = rbXiaoNao.getText().toString();
                    m_alarmType = Symbol.TYPE_XIAONAO;

                } else if (checkedId == rbXiaoLongMao.getId()) {
                    m_alarmName = rbXiaoLongMao.getText().toString();
                    m_alarmType = Symbol.TYPE_XIAOLONGMAO;

                } else if (checkedId == rbXiaoMeiQiu.getId()) {
                    m_alarmName = rbXiaoMeiQiu.getText().toString();
                    m_alarmType = Symbol.TYPE_XIAOMEIQIU;

                } else if (checkedId == rbManulInput.getId()) {
                    m_bNameManulShowed = true;
                    setManulName( alarm );
                    m_alarmType = Symbol.TYPE_MANULINPUT;
                }

                m_tvAlarmName.setText(m_alarmName);
                dialog.dismiss();
                
                alarm.setName(m_alarmName);
                alarm.setType(m_alarmType);
            }
        });
        
        rbXiaoNao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rbXiaoNao.isChecked()) {
                    dialog.dismiss();
                }
            }
        });
        
        rbXiaoLongMao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rbXiaoLongMao.isChecked()) {
                    dialog.dismiss();
                }
            }
        });
        
        rbXiaoMeiQiu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rbXiaoMeiQiu.isChecked()) {
                    dialog.dismiss();
                }
            }
        });
        
        rbManulInput.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rbManulInput.isChecked()) {
                    dialog.dismiss();
                    
                    //already selected on manul input type
                    if (!m_bNameManulShowed) {
                        setManulName(alarm);
                    }
                    //reset
                    m_bNameManulShowed = false;
                }
            }
        });
    }
    public void setGame( final AlarmBean alarm ) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_game, null);
        final CheckBox cb = (CheckBox) layout.findViewById(R.id.gameEnable);
        cb.setChecked(m_gameEnable);
        final Dialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.drawable.white_cloud)
                .setTitle(getString(R.string.alarm_name_title)).setView(layout)
                .setNegativeButton(getString(R.string.cancel), null)
                .setNeutralButton("确定", new android.content.DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						m_gameEnable = cb.isChecked();
						m_tvAlarmName.setText(m_gameEnable==false?"关闭":"开启");
					}
                	
                })
                
                .create();

        dialog.show();
        
     
        
       
    }

    public void setManulName( final AlarmBean alarm ) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_manul_name, null);
        final EditText etAlarmName = (EditText) layout.findViewById(R.id.etAlarmName);

        new AlertDialog.Builder(this)
            .setIcon(R.drawable.white_cloud)
            .setTitle(getString(R.string.please_input))
            .setView(layout)
            .setPositiveButton(getString(R.string.set), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    m_alarmName = etAlarmName.getText().toString();
                    m_tvAlarmName.setText(m_alarmName);
                    
                    alarm.setName(m_alarmName);
                }
            })
            .create()
            .show();
    }

    private void setTimeDialog(final AlarmBean alarm) {
        new TimePickerDialog(this, new OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                // alarm.hour = hourOfDay;
                // alarm.minute = minute;

                m_alarmHours = hourOfDay;
                m_alarmMinutes = minute;

//                m_tvAlarmTime.setText((m_alarmHours < 10 ? "0" + m_alarmHours : m_alarmHours) + ":"
//                        + (m_alarmMinutes < 10 ? "0" + m_alarmMinutes : m_alarmMinutes));
            }
        }, m_alarmHours, m_alarmMinutes, DateFormat.is24HourFormat(this)).show();
    }

    private void setWeeklyDialog(final AlarmBean alarm) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_weeklymode, null);

        final Dialog dialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.alarm_weekly_title)).setView(layout)
                .setIcon(R.drawable.cloud)
                .setNegativeButton(getString(R.string.cancel), null).create();

        dialog.show();

        RadioGroup rgWeeklyMode = (RadioGroup) layout.findViewById(R.id.rgWeeklyMode);
        final RadioButton rbWeeklyEveryday = (RadioButton) layout
                .findViewById(R.id.rbWeeklyEveryday);
        final RadioButton rbWeeklyWeekday = (RadioButton) layout.findViewById(R.id.rbWeeklyWeekday);
        final RadioButton rbWeeklyManul = (RadioButton) layout.findViewById(R.id.rbWeeklyManual);
        final RadioButton rbWeeklyOnce = (RadioButton) layout.findViewById(R.id.rbWeeklyOnce);
        
        //set buttons states
        m_nOccursDay = alarm.getDay();
        switch (m_nOccursDay) {
            case Symbol.DAY_ALLDAY:
                rbWeeklyEveryday.setChecked(true);
                break;
            case Symbol.DAY_WEEKDAY:
                rbWeeklyWeekday.setChecked(true);
                break;
            case Symbol.DAY_ONCE:
                rbWeeklyOnce.setChecked(true);
                break;
            default:
                rbWeeklyManul.setChecked(true);
                break;
        }
        
        rgWeeklyMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbWeeklyEveryday.getId()) {
                    m_alarmWeekly = rbWeeklyEveryday.getText().toString();
                    m_nOccursDay = Symbol.DAY_ALLDAY;

                } else if (checkedId == rbWeeklyWeekday.getId()) {
                    m_alarmWeekly = rbWeeklyWeekday.getText().toString();
                    m_nOccursDay = Symbol.DAY_WEEKDAY;

                } else if (checkedId == rbWeeklyManul.getId()) {
                    m_bWeeklyManulSelected = true;
                    setWeeklyManulDialog( alarm );

                } else if (checkedId == rbWeeklyOnce.getId()) {
                    m_alarmWeekly = rbWeeklyOnce.getText().toString();
                    m_nOccursDay = Symbol.DAY_ONCE;

                }
                
                Log.i("alarm", "set day: " + m_nOccursDay);
                
                alarm.setDay(m_nOccursDay);
                m_tvAlarmWeeklyMode.setText( m_alarmWeekly );

                dialog.dismiss();
            }
        });
        
        rbWeeklyEveryday.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( rbWeeklyEveryday.isChecked() ) {
                    dialog.dismiss();
                }
            }
        });
        
        rbWeeklyWeekday.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( rbWeeklyWeekday.isChecked() ) {
                    dialog.dismiss();
                }
            }
        });
        
        rbWeeklyManul.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                
                if ( !m_bWeeklyManulSelected ) {
                    setWeeklyManulDialog( alarm );
                }
                //reset
                m_bWeeklyManulSelected = false;
            }
        });
        
        rbWeeklyOnce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( rbWeeklyOnce.isChecked() ) {
                    dialog.dismiss();
                }
            }
        });
    }

    private void setWeeklyManulDialog( final AlarmBean alarm ) {
        View layout = LayoutInflater.from(this).inflate(R.layout.alarm_weekly_selector, null);
        final CheckBox cbMon = (CheckBox) layout.findViewById(R.id.cbMon);
        final CheckBox cbTue = (CheckBox) layout.findViewById(R.id.cbTue);
        final CheckBox cbWed = (CheckBox) layout.findViewById(R.id.cbWed);
        final CheckBox cbThu = (CheckBox) layout.findViewById(R.id.cbThu);
        final CheckBox cbFri = (CheckBox) layout.findViewById(R.id.cbFri);
        final CheckBox cbSat = (CheckBox) layout.findViewById(R.id.cbSat);
        final CheckBox cbSun = (CheckBox) layout.findViewById(R.id.cbSun);
        
        //set checkboxs status
        int day = alarm.getDay();
        
        //occurs only once
        if ( (day & Symbol.BIT_ONCE) == 0 ) {
            if ( (day & Symbol.DAY_SUN) != 0 ) {
                cbSun.setChecked(true);
            }
            if ( (day & Symbol.DAY_MON) != 0 ) {
                cbMon.setChecked(true);
            }
            if ( (day & Symbol.DAY_TUE) != 0 ) {
                cbTue.setChecked(true);
            }
            if ( (day & Symbol.DAY_WED) != 0 ) {
                cbWed.setChecked(true);
            }
            if ( (day & Symbol.DAY_THU) != 0 ) {
                cbThu.setChecked(true);
            }
            if ( (day & Symbol.DAY_FRI) != 0 ) {
                cbFri.setChecked(true);
            }
            if ( (day & Symbol.DAY_SAT) != 0 ) {
                cbSat.setChecked(true);
            }
        }

//        final StringBuffer strbuf = new StringBuffer();

        new AlertDialog.Builder(this).setTitle(getString(R.string.alarm_weekly_title))
                .setView(layout)
                .setIcon(R.drawable.cloud)
                .setPositiveButton(getString(R.string.set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "which : " + which);
                        int day = 0;
                        
                        if (cbSun.isChecked()) {
                            day |= Symbol.DAY_SUN;
                        }
                        if (cbMon.isChecked()) {
                            day |= Symbol.DAY_MON;
                        }
                        if (cbTue.isChecked()) {
                            day |= Symbol.DAY_TUE;
                        }
                        if (cbWed.isChecked()) {
                            day |= Symbol.DAY_WED;
                        }
                        if (cbThu.isChecked()) {
                            day |= Symbol.DAY_THU;
                        }
                        if (cbFri.isChecked()) {
                            day |= Symbol.DAY_FRI;
                        }
                        if (cbSat.isChecked()) {
                            day |= Symbol.DAY_SAT;
                        }
                        
                        Log.i(TAG, "set day: " + day);
                        alarm.setDay(day);
                        
                        m_nOccursDay = day;
                        m_tvAlarmWeeklyMode.setText( Utils.FormatDay(day) );
                    }
                })
                .setNegativeButton(getString(R.string.cancel), null)
                .create().show();
    }
    
    private void setOccursDialog(final AlarmBean alarm) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_occurs, null);

        final Dialog dialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.alarm_occurs_title)).setView(layout)
                .setNegativeButton(getString(R.string.cancel), null).create();

        dialog.show();
        
        RadioGroup rgOccursMode = (RadioGroup) layout.findViewById(R.id.rgOccursMode);
        final RadioButton rbOccursOnce = (RadioButton) layout.findViewById(R.id.rbOccursOnce);
        final RadioButton rbOccurs3 = (RadioButton) layout.findViewById(R.id.rbOccurs3);
        final RadioButton rbOccurs5 = (RadioButton) layout.findViewById(R.id.rbOccurs5);
        final RadioButton rbOccursN = (RadioButton) layout.findViewById(R.id.rbOccursN);

        rgOccursMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkedId) {
                if ( checkedId == rbOccursOnce.getId() ) {
                    m_alarmOccurs  = rbOccursOnce.getText().toString();
                    m_nOccurs = 1;
                    
                } else if ( checkedId == rbOccurs3.getId() ) {
                    m_alarmOccurs  = rbOccurs3.getText().toString();
                    m_nOccurs = 3;
                    
                } else if ( checkedId == rbOccurs5.getId() ) {
                    m_alarmOccurs  = rbOccurs5.getText().toString();
                    m_nOccurs = 5;
                    
                } else if ( checkedId == rbOccursN.getId() ) {
                    m_alarmOccurs  = rbOccursN.getText().toString();
                    m_nOccurs = -1;
                    
                }
                
                m_tvAlarmOccursMode.setText(m_alarmOccurs);
                dialog.dismiss();
            }
        });
    }

    private void setIntervalDialog(final AlarmBean alarm) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_interval, null);

        final Dialog dialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.alarm_interval_title)).setView(layout)
                .setNegativeButton(getString(R.string.cancel), null).create();

        dialog.show();
        
        RadioGroup rgIntervalMode = (RadioGroup) layout.findViewById(R.id.rgIntervalMode);
        final RadioButton rbAfter5min = (RadioButton) layout.findViewById(R.id.rbAfter5min);
        final RadioButton rbAfter10min = (RadioButton) layout.findViewById(R.id.rbAfter10min);
        final RadioButton rbAfter15min = (RadioButton) layout.findViewById(R.id.rbAfter15min);

        rgIntervalMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkedId) {
                if ( checkedId == rbAfter5min.getId() ) {
                    m_alarmInterval  = rbAfter5min.getText().toString();
                    m_nInterval = 5;
                    
                } else if ( checkedId == rbAfter10min.getId() ) {
                    m_alarmInterval  = rbAfter10min.getText().toString();
                    m_nInterval = 10;
                    
                } else if ( checkedId == rbAfter15min.getId() ) {
                    m_alarmInterval  = rbAfter15min.getText().toString();
                    m_nInterval = 15;
                    
                }
                
                m_tvAlarmOccursMode.setText(m_alarmInterval);
                dialog.dismiss();
            }
        });
    }
    
    private void setAlarmRingDialog( final AlarmBean alarm ) {
        View layout = LayoutInflater.from(this).inflate(R.layout.set_alarm_ring, null);

        final Dialog dialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.alarm_ring_title)).setView(layout)
                .setIcon(R.drawable.bird)
                .setPositiveButton(getString(R.string.set), null)
                .setNegativeButton(getString(R.string.cancel), null)
                .create();

        dialog.show();
        
        RadioGroup rgRingMode = (RadioGroup) layout.findViewById(R.id.rgRingMode);
        
        final RadioButton rbRingSilent = (RadioButton) layout.findViewById(R.id.rbSilent);
        final RadioButton rbRingSystem = (RadioButton) layout.findViewById(R.id.rbSystemRing);
//        final RadioButton rbRingOptional = (RadioButton) layout.findViewById(R.id.rbRingOptional);
        
        final CheckBox cbVibrate = (CheckBox) layout.findViewById(R.id.cbVibrate);
        
        //show ring mode status
        final int mode = alarm.getRingMode();
        switch (mode) {
            case Symbol.RING_SLIENT:
                rbRingSilent.setChecked(true);
                break;
            case Symbol.RING_SYSTEM:
                rbRingSystem.setChecked(true);
                break;
            /*case Symbol.RING_OPTIONAL:
                rbRingOptional.setChecked(true);
                break;*/
        }
        
        //show vibrate status
        if (alarm.getVibrate()) {
            cbVibrate.setChecked(true);
        }
        
        rgRingMode.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkedId) {
                if ( checkedId == rbRingSilent.getId() ) {
                    m_alarmRingMode = rbRingSilent.getText().toString();
                    m_nRingMode = Symbol.RING_SLIENT;
                    m_ringUri = null;
                    
                } else if ( checkedId == rbRingSystem.getId() ) {
                    m_alarmRingMode = rbRingSystem.getText().toString();
                    m_nRingMode = Symbol.RING_SYSTEM;
                    
                }/* else if ( checkedId == rbRingOptional.getId() ) {
                    m_alarmRingMode = rbRingOptional.getText().toString();
                    m_nRingMode = Symbol.RING_OPTIONAL;
                    
                }*/
                
                m_tvAlarmRingMode.setText( m_alarmRingMode );
                alarm.setRingMode(m_nRingMode);
                
                dialog.dismiss();
            }
        });
        
        rbRingSilent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( rbRingSilent.isChecked() ) {
                    dialog.dismiss();
                }
                m_ringUri = null;
            }
        });
        
        rbRingSystem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( rbRingSystem.isChecked() ) {
                    dialog.dismiss();
                }
                openSystemRingtone( alarm );
            }
        });
        
        cbVibrate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( cbVibrate.isChecked() ) {
                    m_bVibrate = true;
                    alarm.setVibrate(true);
                } else {
                    m_bVibrate = false;
                    alarm.setVibrate(false);
                }
            }
        });
    }
    
    private void openSystemRingtone( AlarmBean alarm ) {
        Intent intent = new Intent(android.media.RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_TYPE, android.media.RingtoneManager.TYPE_RINGTONE);
        
//        startActivity(intent);
        startActivityForResult(intent, TYPE_ALARM);
    }

    private OnClickListener oclButtons = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btFinish:
                    save();
                    finish();
                    break;

                case R.id.btBack:
                    finish();
                    break;
            }
        }
    };

    private void save() {
    	m_alarmHours=wlh.getCurrentItem();
    	m_alarmMinutes = wlm.getCurrentItem();
        Calendar cl = Utils.setCalendarTime(m_alarmHours, m_alarmMinutes);
        Log.i(TAG, "save--- ringMode: " + m_nRingMode + " , uri: " + m_ringUri);
        
        //enable the alarm
        m_bEnable = true;
       
        AlarmBean alarmBean = new AlarmBean(
                m_alarmType, m_alarmName,
                Symbol.INTERVAL_DAY, m_nOccursDay, m_alarmIndex,
                cl.getTimeInMillis(), m_bEnable,
                m_nRingMode, m_ringUri,
                m_nInterval, m_bVibrate,m_gameEnable,form);
        AlarmProvider.geInstance(this).setAlarm(alarmBean);

        //重置闹铃时间
        AlarmSet.setAlarm(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "resultCode : " + resultCode + ", requestCode: " + requestCode);
        if ( resultCode != RESULT_OK ) {
        	
            return;
        } else {
            Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            Log.i(TAG, "uri : " + uri);
            
            if ( uri != null ) {
                m_ringUri = uri.toString();
                /*if ( m_ringUri != null ) {
                    m_alarm.setUri(m_ringUri);
                }*/
                
//                switch ( requestCode ) {
//                    case TYPE_ALARM:
//                        RingtoneManager.setActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_ALARM, uri);
//                        break;
//                }
            }
        }
    }
}
